package thread;

/*
 * @author zzr
 * @date: 2025/04/04  22:42
 * @description:
 */

// 为了简单，此处 MyBlockingQueue 不写做泛型的样式，考虑存储的元素就是单纯的 String
class MyBlockingQueue {
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        this.elems = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (locker) {

            while (size >= elems.length) {
                // 队列满了
                // 后续我们需要让这个代码能够阻塞
                locker.wait();
            }
            // 新的元素要放到 tail 指向的位置上
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                tail = 0;
            }
            size++;

            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        String elem = null;
        synchronized(locker) {
            while(size == 0){
                // 队列空了，让这个代码阻塞
                locker.wait();
            }
            // 取出 head 位置的元素并返回
            elem = elems[head];
            head++;
            if(head >= elems.length) {
                head = 0;
            }
            // 注意不要忘记 size
            size--;

            // 元素出队列成功之后，唤醒
            locker.notify();
        }
        return elem;
    }
}

public class ThreadDemo39 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(1000);

        // 生产者
        Thread t1 = new Thread(() -> {
            int n = 1;
            while (true) {
                try {
                    myBlockingQueue.put(n + "");
                    System.out.println("生产元素 " + n);
                    n++;
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        //消费者
        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    String n = myBlockingQueue.take();
                    System.out.println("消费元素" + n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
